<template>
<div>
    <div v-show="!connected" class="shrink0 row gap15 center" style="margin-top: 10px; color:red">
        请先连接到主机零件
    </div>
    <div class="shrink0 row gap15" style="margin-top: 10px">
        <n-input-group style="width:250px">
            <n-input-group-label>ws://</n-input-group-label>
            <n-input v-model:value="poster.addr" placeholder="主机零件 IP" />
            <n-input-group-label>:8022</n-input-group-label>
        </n-input-group>
        <n-button v-show="poster.connStatus=='disconnected'" type="info" @click="projection" :disabled="!connected">音画投送</n-button>
        <n-button v-show="poster.connStatus=='connected' || poster.connStatus=='connecting'" type="warning" @click="poster.stopProjection()">停止投送</n-button>
        <n-button v-if="isDebug" type="info" @click="poster.projection(false)" :disabled="!connected">单帧</n-button>
        <span class="grow"></span>
        <n-button quaternary @click="bShowRecording=!bShowRecording" v-if="isDebug">录播</n-button>
        <n-button quaternary @click="bShowAdvanceed=!bShowAdvanceed">高级</n-button>
    </div>

    <div v-show="bShowAdvanceed" style="margin-top:20px" class="column gap10">

        <div class="row gap10 item-center">
            <span style="width:60px">品质</span>
            <n-slider style="width:400px" v-model:value="quality" :step="1" />
        </div>

        <!-- <div class="row gap10 item-center">
            <span style="width:60px">音量</span>
            <n-slider style="width:400px" v-model:value="quality" :step="1" />
        </div> -->

        <div class="row">
            <span style="" class="shrink0">视频帧率：{{ poster.fps }}</span>
            <span style="margin-left:25px" class="shrink0">音频码率：{{ formatBitrate(poster.bitrate) }}</span>
            <span v-if="isDebug" style="margin-left:25px" class="shrink0">{{ poster.audio_post_times }}</span>
        </div>

        <div v-if="isDebug" class="row gap15 item-center">
            <n-button @click="poster.videoFrameSaveAsFile()" type="text" >Save</n-button>
            <n-button @click="bus.emit('terminal.popup()')" type="text">终端</n-button>
        </div>
    </div>

    <div v-show="bShowRecording" style="margin-top:20px" class="column gap10">

        <div class="row item-center gap15">
            <n-button v-show="!frameBuffer.savingFrames" @click="startSaveFrames">保存为RAW</n-button>
            
            <n-button v-show="!frameBuffer.savingFrames" @click="startSaveFrames">保存为帧序列</n-button>
            <n-button v-show="frameBuffer.savingFrames" @click="stopSaveFrames">停止保存</n-button>
            <span>{{frameBuffer.savedFrameNum}}帧 / {{recordedSec}}秒</span>
        </div>

        <div v-if="isDebug" class="row gap15 item-center">
            <div class="row item-center gap5 shrink0">
                <span>回放帧率: </span>
                <n-input-number class="" style="width: 100px" v-model:value="replayFPS"></n-input-number>
            </div>
            <span class="grow"></span>
            <n-button v-show="!frameBuffer?.recording" @click="startRecording" type="text">开始录制</n-button>

            <span v-show="frameBuffer?.recording">{{recordedSec}}秒</span>
            <n-button v-show="frameBuffer?.recording" @click="stopRecording" type="text">停止录制</n-button>
        </div>
        
        <div v-if="isDebug" class="column gap5 item-center">

            <div v-for="record, recordIdx in (frameBuffer?.recordedFrames||[])" class="row gap15 item-center" style="padding-left: 20px;">
                <span style="width: 80px">{{record.type}}</span>
                <span style="width: 160px">已录帧数 {{record.frames.length}}</span>
                <n-input class="" style="width: 200px" v-model:value="record.desc"></n-input>
                <n-button v-show="!frameBuffer?.recording && frameBuffer?.replayRecordIdx==-1 && record.frames.length" @click="replay(recordIdx)" type="text">回放</n-button>
                <n-button v-show="frameBuffer?.replayRecordIdx==recordIdx" @click="stopReplay" type="text">停止回放 {{frameBuffer?.replayFrmIdx}}</n-button>
                <n-button v-show="frameBuffer?.replayRecordIdx!=recordIdx" @click="deleteRecord(recordIdx)" type="text">删除</n-button>
                <n-button v-show="frameBuffer?.replayRecordIdx!=recordIdx" @click="deleteRecord(recordIdx)" type="text">保存帧序列</n-button>
            </div>
            
        </div>
    </div>
</div>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, inject, reactive } from 'vue'
import {isDebug} from '../../issue'
import { bus } from '@beshell/events-ts/bus';
import {Poster} from './Poster'
import { FrameBuffer } from './FrameBuffer';
import { CaptureBase } from './Capture';
import { conn } from '@beshell/conn-ts/Connection';


const activeCapture = inject("activeCapture") as Ref<CaptureBase>
const quality = inject("quality")
const frameBuffer = reactive(inject<FrameBuffer>("frameBuffer") as any)
// const refFrameBuffer = ref(frameBuffer)

const addr = ref(null)
const poster = reactive(new Poster(frameBuffer as FrameBuffer))

const bShowAdvanceed = ref(false)
const bShowRecording = ref(false)

const connected = ref(false)

// 录播回放帧率
const replayFPS = ref(10)
let recordingTimer = -1
let replayTimer = -1
const recordedSec = ref(0)
const replayRecordIdx = ref(-1)

function projection() {
    console.log(activeCapture.value.audioRecorder)
    if(activeCapture.value.audioRecorder) {
        poster.setAudioRecorder(activeCapture.value.audioRecorder)
    }
    activeCapture.value.onStartProjection()
    poster.projection( activeCapture.value.isContinuous() )
}

function formatBitrate(bitrate) {
    if(bitrate>1000000) {
        return Math.round(bitrate/1000000) + ' Mbps'
    }
    else if(bitrate>1000) {
        return Math.round(bitrate/1000) + ' Kbps'
    }
    else {
        return bitrate + ' bps'
    }
}

onMounted(()=>{
    ;(window as any).poster = poster
    ;(window as any).frameBuffer = frameBuffer

    bus.on("projection.start()", projection)
    bus.on("projection.stop()", ()=>poster.stopProjection())

    conn.on("status", status=>{
        connected.value = status == 'connected'
    })
})

function startTimer() {
    let startTime = Date.now()
    recordingTimer = setInterval(()=>{
        recordedSec.value = Math.round((Date.now()-startTime)/1000)
    }, 1000) as unknown as number
}
function stopTimer() {
    clearTimeout(recordingTimer)
    recordingTimer = -1
}

// 投屏源录播
function startRecording() {
    if(!frameBuffer) {
        return
    }
    frameBuffer.startRecord(activeCapture.value.type)
    recordedSec.value = 0

    startTimer()
}
function stopRecording() {
    frameBuffer.stopRecord()
    stopTimer()
}

function replay(recordIdx) {
    if(!frameBuffer) {
        return
    }
    frameBuffer.replay(recordIdx)

    replayTimer = setInterval(()=>{
        poster.projection(false)
    }, 1000/replayFPS.value) as unknown as number
}

function stopReplay() {
    if(!frameBuffer) {
        return
    }
    frameBuffer.stopReplay()

    clearTimeout(replayTimer)
    replayTimer = -1

    poster.stopProjection()
}

function deleteRecord(recordIdx) {
    if(!confirm("确定要删除这个录制吗")){
        return
    }
    frameBuffer.recordedFrames.splice(recordIdx,1)
}

function startSaveFrames() {
    frameBuffer.startSaveFrames() 
    startTimer()
}
function stopSaveFrames() {
    frameBuffer.stopSaveFrames() 
    stopTimer()
}

async function onenter() {
    if(conn.isConnected) {
        try{
            let staIP = await conn.console.call(`WiFi.status('sta').ip`)
            if(staIP) {
                poster.setAddr(staIP)
            }
        }catch(e) {
            console.error(e)
        }
    }
}

defineExpose({onenter})

</script>